/**
 * Created by rockyren on 14/12/22.
 */
define(['mindmapJS/ng/module', 'mindmapJS/imp/Graph', 'mindmapJS/imp/Renderer', 'mindmapJS/imp/renderModule/Toolbar'],
  function(mindmapModule, Graph, Renderer, Toolbar){
  mindmapModule.directive('mindmap', ['$state', 'mindmapModuleBaseUrl',
    function($state, mindmapModuleBaseUrl){

    return {
      restrict: 'EA',
      templateUrl: mindmapModuleBaseUrl + 'tpls/mindmap.html',
      scope: {
        createTask: '&',
        deleteTask: '&',
        firstLevelList: '=firstLevelList',
        handleNode: '=handleNode',
        currentProjectInfo: '='
      },
      link: function(scope){
        //对外暴露的结点的操作模块
        scope.handleNode = {
          addNode: function(name, outerId){
            var node = graph.addNode();
            node.setParent(graph.selected);
            node.label = name;
            node.outerId = outerId;
            node.render();
          },
          deleteNode: function(){
            if(graph.selected){
              if(graph.selected.isRootNode()) {
                console.log('cannot cancel root node');
              }else{

                graph.selected.remove();
                graph.setSelected(null);
              }
            }
          }
        };

        //初始化渲染类和graph类
        var gRenderer = new Renderer('mindmap-canvas', 'toolbar');
        var graph = new Graph(gRenderer);


        //初始化根结点
        var rootNode = graph.addNode({
          x: gRenderer.canvasWidth/2 - 50,
          y: 200
        });

        rootNode.label = scope.currentProjectInfo['baseInfo']['name'];
        graph.setRootNode(rootNode);
        graph.root.render();
        gRenderer.setShape(rootNode, {shapeType: 'root'});

        //初始化子结点
        graph.fromJsonObj(scope.firstLevelList);


        scope.nodePlus = function(){
          var selectedNode = graph.selected;
          var parentTaskInfo = null;

          if( ! selectedNode.isRootNode() ){
            parentTaskInfo = {
              id: selectedNode.outerId,
              label: selectedNode.label
            };
          }

          scope.createTask({
            parentTaskInfo: parentTaskInfo
          });
        };

        scope.nodeCancel = function(){
          if( confirm('删除后无法恢复，您确定要执行吗？')){
            scope.deleteTask({
              taskId: graph.selected.outerId
            });
          }

        };

        scope.nodeEdit = function(){
          $state.go('project.show.desktop.taskInfo', {taskId: graph.selected.outerId});
        }
      }
    }
  }])
});